package com.origin.file.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.origin.common.exception.QiwenException;
import com.origin.common.operation.FileOperation;
import com.origin.common.util.security.SessionUtil;
import com.origin.file.component.AsyncTaskComp;
import com.origin.file.component.FileDealComp;
import com.origin.file.entity.domain.Music;
import com.origin.file.entity.domain.UserFile;
import com.origin.file.entity.vo.file.FileDetailVO;
import com.origin.file.mapper.MusicMapper;
import com.origin.file.mapper.UserFileMapper;
import com.origin.file.service.IFileService;
import com.origin.file.util.QiwenFileUtil;
import com.origin.oss.entity.FileInfo;
import com.origin.oss.entity.ImageInfo;
import com.origin.oss.factory.FileUploaderFactory;
import com.origin.oss.operation.download.Downloader;
import com.origin.oss.operation.download.domain.DownloadFile;
import com.origin.oss.service.FileInfoService;
import com.origin.oss.service.ImageInfoService;
import com.origin.oss.util.FileStorageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author origin
 */
@Service
@Slf4j
public class FileService implements IFileService {
    @Resource
    UserFileMapper userFileMapper;
    @Resource
    FileUploaderFactory ufopFactory;

    @Resource
    private FileInfoService fileInfoService;

    @Resource
    AsyncTaskComp asyncTaskComp;
    @Resource
    MusicMapper musicMapper;
    @Resource
    private ImageInfoService imageInfoService;
    @Resource
    FileDealComp fileDealComp;

    @Override
    public void unzipFile(String userFileId, int unzipMode, String filePath) {
        UserFile userFile = userFileMapper.selectById(userFileId);
        FileInfo fileBean = fileInfoService.getByFileId(userFile.getFileId());
        File destFile = new File(FileStorageUtils.getStaticPath() + "temp" + File.separator + fileBean.getFileUrl());

        Downloader downloader = ufopFactory.getDownloader(fileBean.getStorageType());
        DownloadFile downloadFile = new DownloadFile();
        downloadFile.setFileUrl(fileBean.getFileUrl());
        InputStream inputStream = downloader.getInputStream(downloadFile);

        try {
            FileUtils.copyInputStreamToFile(inputStream, destFile);
        } catch (IOException e) {
            log.error("", e);
        }


        String extendName = userFile.getExtendName();

        String unzipUrl = FileStorageUtils.getTempFile(fileBean.getFileUrl()).getAbsolutePath().replace("." + extendName, "");

        List<String> fileEntryNameList = new ArrayList<>();

        try {
            fileEntryNameList = FileOperation.unzip(destFile, unzipUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解压失败" + e);
            throw new QiwenException(500001, "解压异常：" + e.getMessage());
        }

        if (destFile.exists()) {
            destFile.delete();
        }

        if (!fileEntryNameList.isEmpty() && unzipMode == 1) {
            UserFile qiwenDir = QiwenFileUtil.getQiwenDir(userFile.getUserId(), userFile.getFilePath(), userFile.getFileName());
            userFileMapper.insert(qiwenDir);
        }
        for (String entryName : fileEntryNameList) {
            asyncTaskComp.saveUnzipFile(userFile, fileBean, unzipMode, entryName, filePath);

        }
    }

    @Override
    public void updateFileDetail(String userFileId, String identifier, long fileSize) {
        UserFile userFile = userFileMapper.selectById(userFileId);
//        FileBean fileBean = new FileBean();
//        fileBean.setIdentifier(identifier);
//        fileBean.setFileSize(fileSize);
//        fileBean.setModifyTime(currentTime);
//        fileBean.setModifyUserId(SessionUtil.getUserId());
//        fileBean.setFileId(userFile.getFileId());
//        fileMapper.updateById(fileBean);
        userFile.setUploadDateTime(LocalDateTime.now());
        userFile.setModifyDateTime(LocalDateTime.now());
        userFile.setModifyUserId(SessionUtil.getUserId());
        userFileMapper.updateById(userFile);
    }

    @Override
    public FileDetailVO getFileDetail(String userFileId) {
        UserFile userFile = userFileMapper.selectById(userFileId);
        FileInfo fileBean = fileInfoService.getByFileId(userFile.getFileId());
        Music music = musicMapper.selectOne(new QueryWrapper<Music>().eq("fileId", userFile.getFileId()));
        ImageInfo image = imageInfoService.getByFileId(userFile.getFileId());

        if ("mp3".equalsIgnoreCase(userFile.getExtendName()) || "flac".equalsIgnoreCase(userFile.getExtendName())) {
            if (music == null) {
                fileDealComp.parseMusicFile(userFile.getExtendName(), fileBean.getStorageType(), fileBean.getFileUrl(), fileBean.getFileId());
                music = musicMapper.selectOne(new QueryWrapper<Music>().eq("fileId", userFile.getFileId()));
            }
        }

        FileDetailVO fileDetailVO = new FileDetailVO();
        BeanUtil.copyProperties(userFile, fileDetailVO);
        BeanUtil.copyProperties(fileBean, fileDetailVO);
        fileDetailVO.setMusic(music);
        fileDetailVO.setImage(image);
        return fileDetailVO;
    }

}
